package app1.rapidsquare.com.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

import app1.rapidsquare.com.Utility.Utility;
import app1.rapidsquare.com.activity.R;
import app1.rapidsquare.com.classes.User;
import app1.rapidsquare.com.core.ConnectionDetector;
import eu.inmite.android.lib.validations.form.FormValidator;
import eu.inmite.android.lib.validations.form.annotations.NotEmpty;
import eu.inmite.android.lib.validations.form.annotations.RegExp;
import eu.inmite.android.lib.validations.form.callback.SimpleErrorPopupCallback;

import static eu.inmite.android.lib.validations.form.annotations.RegExp.EMAIL;

public class LoginActivity extends ActionBarActivity {

    @NotEmpty(messageId = R.string.validation_valid_email, order = 1)
    @RegExp(value = EMAIL, messageId = R.string.validation_valid_email, order = 1)
    private AutoCompleteTextView mUserName;

    @NotEmpty(messageId = R.string.validation_name, order = 2)
    private EditText mPassword;


    private EditText mConfirmPassword;
    private Button mButtonSignIn, mButtonNewUser;
    private ConnectionDetector mConnectionDetector;
    protected StringEntity mHttpEntity;
    private TextView mTextViewInternetConnection;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        mConnectionDetector = new ConnectionDetector();
        LoadActionBar();
        mProgressDialog = new ProgressDialog(LoginActivity.this);
        mProgressDialog.setMessage("Please wait");

        mUserName = (AutoCompleteTextView) findViewById(R.id.email);
        mPassword = (EditText) findViewById(R.id.password);
        mConfirmPassword = (EditText) findViewById(R.id.confirmPassword);

        mButtonSignIn = (Button) findViewById(R.id.email_sign_in_button);
        mButtonNewUser = (Button) findViewById(R.id.buttonNewUser);
        mButtonNewUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mConfirmPassword.setVisibility(View.VISIBLE);
                mButtonNewUser.setVisibility(View.GONE);
                LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT, 1.0f);
                mButtonSignIn.setLayoutParams(param);
            }
        });

        mButtonSignIn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                validate();
            }
        });
        mTextViewInternetConnection = (TextView) findViewById(R.id.textViewInternetConnection);
        mTextViewInternetConnection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTextViewInternetConnection.setVisibility(View.GONE);
            }
        });
    }

    private void LoadActionBar() {
        ActionBar mActionBar = getSupportActionBar();
        if (mActionBar != null) {
            mActionBar.setDisplayShowHomeEnabled(false);
            mActionBar.setHomeButtonEnabled(false);
            mActionBar.setDisplayShowTitleEnabled(false);
            LayoutInflater mInflater = LayoutInflater.from(this);

            View mCustomView = mInflater.inflate(R.layout.action_bar_with_back, null);

            ImageView mImageViewBack = (ImageView) mCustomView
                    .findViewById(R.id.textViewBack);
            mImageViewBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onBackPressed();
                }
            });


            mActionBar.setCustomView(mCustomView);
            mActionBar.setDisplayShowCustomEnabled(true);
        }
    }

    protected boolean IsAvailableInternet() {
        return mConnectionDetector.getConnectingStatus();
    }


    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(
                mConnectionDetector,
                new IntentFilter(
                        android.net.ConnectivityManager.CONNECTIVITY_ACTION));
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mConnectionDetector);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(Activity.RESULT_CANCELED);
        finish();
    }

    @Override
    public void onStop() {
        super.onStop();
        FormValidator.stopLiveValidation(this);
    }

    private void validate() {
        boolean isValid = FormValidator.validate(this,
                new SimpleErrorPopupCallback(this, true));

        boolean mIsNewUser = mConfirmPassword.getVisibility() == View.VISIBLE;

        if (isValid && mIsNewUser) {
            if (!mPassword.getText().toString().equals(mConfirmPassword.getText().toString())) {
                Toast.makeText(LoginActivity.this, getResources().getString(R.string.password_are_not_equal_message), Toast.LENGTH_SHORT).show();
                return;
            }

            CheckEmail();
        }

        if (!mIsNewUser && isValid) {
            InputMethodManager inputManager = (InputMethodManager) LoginActivity.this
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(this.getCurrentFocus()
                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            Login();
        }

    }

    private void CheckEmail() {
        if (IsAvailableInternet()) {
            mTextViewInternetConnection.setVisibility(View.GONE);
            mProgressDialog.show();
            new AsyncTask<Void, Void, String>() {

                @Override
                protected String doInBackground(Void... params) {
                    try {

                        return Utility.ConnectServer(Utility.CHECK_EMAIL_URL + "?email=" + mUserName.getText().toString(), Utility.RequestMethodType.GET, null);
                    } catch (Exception ex) {
                        Utility.Log("Error is connection to the service", ex);
                        return null;
                    }
                }

                @Override
                protected void onPostExecute(String result) {
                    if (!Utility.isNullOrEmpty(result)) {
                        try {
                            JSONObject resultJsonObject = new JSONObject(result);
                            if (!resultJsonObject.has("Error")) {
                                String resultObject = resultJsonObject
                                        .getString("Result");
                                if (!Utility.isNullOrEmpty(resultObject) && !Boolean.valueOf(resultObject))
                                    Login();
                                else
                                    Toast.makeText(LoginActivity.this, "Please choose an another email", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException ex) {
                            Utility.Log("Check email convert String to Json in LoginActivity", ex);
                        }
                    }

                    mProgressDialog.dismiss();
                }
            }.execute();

        } else

        {
            mTextViewInternetConnection.setVisibility(View.VISIBLE);
            return;
        }

    }

    private void Login() {
        if (IsAvailableInternet()) {
            mTextViewInternetConnection.setVisibility(View.GONE);
            try {
                boolean mIsNewUser = mConfirmPassword.getVisibility() == View.VISIBLE;
                User profile = Utility.getUserSession(LoginActivity.this);

                JSONObject postObject = new JSONObject();
                postObject.accumulate("Email", mUserName.getText().toString());
                postObject
                        .accumulate("Password", mPassword.getText().toString());
                postObject.accumulate("SocialType", 0);
                postObject.accumulate("IsCheck", !mIsNewUser);
                postObject.accumulate("DeviceOs", 1);
                postObject.accumulate("DeviceId", profile.DeviceId);
                postObject.accumulate("MobileWorkingSystem", 2);

                this.mHttpEntity = new StringEntity(postObject.toString());

                SendRequest();

            } catch (JSONException e) {
                Utility.Log("Login Activity json convert to object", e);

            } catch (UnsupportedEncodingException e) {
                Utility.Log("Login Activity unsupported encoding ", e);
            }
        } else
            mTextViewInternetConnection.setVisibility(View.VISIBLE);
    }

    protected void getResponce(String jsonResult) {

        if (!Utility.isNullOrEmpty(jsonResult)) {
            try {

                JSONObject resultJsonObject = new JSONObject(jsonResult);
                if (resultJsonObject.has("Error")) {
                    String error = resultJsonObject.getString("Error");

                    if (Utility.isNullOrEmpty(error)) {
                        String resultObject = resultJsonObject
                                .getString("Result");
                        User userDetails = Utility
                                .Deserialize(User.class, resultObject);

                        if (userDetails != null
                                && !Utility
                                .isNullOrEmpty(userDetails.UserToken)) {
                            userDetails.Email = mUserName.getText().toString().trim();
                            userDetails.Password = mPassword.getText().toString().trim();

                            setResult(Activity.RESULT_OK, new Intent().putExtra(Utility.LOGIN_INTENT_DATA_NAME, userDetails));
                            finish();
                        }
                    } else {
                        Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
                    }

                } else {

                }
            } catch (JSONException e) {
                Utility.Log("Login Activity error conver json to object ", e);
            }
        }
    }

    private synchronized void SendRequest() {

        if (IsAvailableInternet()) {
            mProgressDialog.show();
            new AsyncTask<Void, Void, String>() {

                @Override
                protected String doInBackground(Void... params) {
                    return Utility.ConnectServer(Utility.LOGIN_URL, Utility.RequestMethodType.POST, mHttpEntity);
                }

                @Override
                protected void onPostExecute(String result) {
                    getResponce(result);
                    mProgressDialog.dismiss();
                }
            }.execute();

        }
    }
}



